import { glob } from 'glob'
import config, { saveConfig } from '../config/index.js'
import deepseek from '../lib/deepseek/deepseek.js'
import fsPromises from 'fs/promises'
import { writingAnalysisReport } from '../lib/llm/prompt.js'
import path from 'path'

import { sleep, extractJsonFromText } from '../util.js'

class API {
  async go(ctx) {
    deepseek.go()

    ctx.body = 'success'
  }

  // 提取渗透攻击方法与缓解措施
  async text(ctx) {
    ctx.body = 'success'

    setTimeout(async () => {
      const data = config.chat.ruby
      let files = await glob(data.src)

      for (let i = data.index; i < files.length; i++) {
        // 进度
        console.log(`${i}/${files.length}`, ((i / files.length) * 100).toFixed(2))

        data.index = i
        saveConfig()

        const text = await fsPromises.readFile(files[i], 'utf-8')
        const outputPath = path.join(data.dist, path.parse(files[i]).name + '-' + Date.now())
        // const result = await dbWeb.prompt(extractPrompt + text)
        const result = await dbWeb.prompt(writingAnalysisReport + text)

        console.log('结果', result)

        try {
          // 转义处理
          const fixedResult = result
            .replace(/\\([^"\\/bfnrtu])/g, '\\\\$1')
            // 零宽空格/不可见控制字符
            .replace(/[\u200B-\u200D\uFEFF]/g, '')

          console.log('fixedResult', fixedResult)

          const json = JSON.parse(fixedResult)

          await fsPromises.writeFile(outputPath + '.json', JSON.stringify(json.extract, null, 2))
        } catch (e) {
          console.error('json parse error，直接保存', e)
          fsPromises.writeFile(outputPath + '-error.json', result)
        }

        await sleep(45 * 1000)
      }
    }, 0)
  }

  async chat(ctx) {
    ctx.body = 'success'

    setTimeout(async () => {
      try {
        let result = await deepseek.prompt(writingAnalysisReport)
        await saveJson(result)

        for (let i = 0; i < 100; i++) {
          console.log('开始循环')
          let result = await deepseek.conversation('继续，不要重复')
          await saveJson(result)
        }
      } catch (e) {
        console.error('Error occurred while saving JSON:', e)
        throw e
      }
    }, 0)
  }

  async conversation(ctx) {
    ctx.body = 'success'

    setTimeout(async () => {
      let result = await deepseek.conversation('继续，不要重复')
      await saveJson(result.extract)
    }, 0)
  }
}

async function saveJson(text) {
  const json = extractJsonFromText(text)
  console.log('提取结果', json)
  await fsPromises.writeFile('./data/json/' + Date.now() + '.json', JSON.stringify(json, null, 2))
}

export default new API()
